from django.db import models
import hashlib
from django.contrib.auth.models import AbstractUser
from utils.models import CoreModel, table_prefix
from system.role.models import Role


class Users(AbstractUser, CoreModel):
    username = models.CharField(max_length=150, unique=True, db_index=True, verbose_name='用户账号', help_text="用户账号")
    email = models.EmailField(max_length=255, verbose_name="邮箱", null=True, blank=True, help_text="邮箱")
    mobile = models.CharField(max_length=255, verbose_name="电话", null=True, blank=True, help_text="电话")
    nickname = models.CharField(max_length=40, verbose_name="姓名", help_text="姓名")
    role = models.ForeignKey(to=Role, on_delete=models.PROTECT, verbose_name='关联角色', help_text="关联角色",
                             related_name='role', null=True,
                             blank=True)

    def set_password(self, raw_password):
        super().set_password(hashlib.md5(raw_password.encode(encoding='UTF-8')).hexdigest())

    class Meta:
        db_table = table_prefix + "user"
        verbose_name = '用户表'
        verbose_name_plural = verbose_name
        ordering = ('-create_datetime',)
